import { useState } from 'react'
import { 
  Button, 
  Input, 
  Upload, 
  message, 
  Spin, 
  Modal,
  Card,
  Space
} from 'antd'
import { 
  UploadOutlined, 
  ThunderboltOutlined,
  CopyOutlined,
  LeftOutlined,
  FileImageOutlined
} from '@ant-design/icons'
import { useNavigate } from 'react-router-dom'
import { templates } from '../data/templates'
import { formatArticle } from '../services/formatService'
import './EditorPage.css'

const { TextArea } = Input

function EditorPage() {
  const navigate = useNavigate()
  const [content, setContent] = useState('')
  const [images, setImages] = useState([])
  const [selectedTemplate, setSelectedTemplate] = useState(null)
  const [previewHTML, setPreviewHTML] = useState('')
  const [loading, setLoading] = useState(false)

  // 处理图片上传
  const handleImageUpload = async ({ file, onSuccess, onError }) => {
    try {
      // 先用base64预览（快速反馈）
      const reader = new FileReader()
      reader.onload = (e) => {
        setImages(prev => [...prev, {
          url: e.target.result,
          name: file.name,
          file: file
        }])
      }
      reader.readAsDataURL(file)
      
      // 实际上传到服务器（可选，MVP阶段可以只用base64）
      // import { uploadImage } from '../services/apiService'
      // const result = await uploadImage(file)
      // if (result.success) {
      //   setImages(prev => prev.map(img => 
      //     img.name === file.name ? { ...img, url: result.data.url } : img
      //   ))
      // }
      
      onSuccess('ok')
    } catch (error) {
      message.error('图片上传失败')
      onError(error)
    }
    return false
  }

  // 一键排版
  const handleFormat = async () => {
    if (!content.trim()) {
      message.warning('请先输入文章内容')
      return
    }

    if (!selectedTemplate) {
      message.warning('请选择一个模板')
      return
    }

    setLoading(true)
    try {
      // 调用排版服务
      const html = await formatArticle(content, images, selectedTemplate)
      setPreviewHTML(html)
      message.success('排版完成！')
    } catch (error) {
      message.error('排版失败，请重试')
      console.error(error)
    } finally {
      setLoading(false)
    }
  }

  // 复制到公众号
  const handleCopy = () => {
    if (!previewHTML) {
      message.warning('请先完成排版')
      return
    }

    // 创建临时元素
    const tempDiv = document.createElement('div')
    tempDiv.innerHTML = previewHTML
    tempDiv.style.position = 'absolute'
    tempDiv.style.left = '-9999px'
    document.body.appendChild(tempDiv)

    // 选择内容
    const range = document.createRange()
    range.selectNodeContents(tempDiv)
    const selection = window.getSelection()
    selection.removeAllRanges()
    selection.addRange(range)

    // 复制
    try {
      document.execCommand('copy')
      message.success('已复制到剪贴板！请在公众号后台粘贴（Ctrl+V）')
      
      // 显示使用说明
      Modal.info({
        title: '使用说明',
        content: (
          <div style={{ lineHeight: 1.8 }}>
            <p>1. 打开微信公众号后台</p>
            <p>2. 新建图文消息</p>
            <p>3. 在编辑器中按 <strong>Ctrl+V</strong> 粘贴</p>
            <p>4. 完成！格式完美保留</p>
          </div>
        )
      })
    } catch (error) {
      message.error('复制失败，请手动选择内容复制')
    } finally {
      selection.removeAllRanges()
      document.body.removeChild(tempDiv)
    }
  }

  return (
    <div className="editor-page">
      {/* 顶部工具栏 */}
      <header className="editor-header">
        <div className="header-left">
          <Button 
            type="text" 
            icon={<LeftOutlined />}
            onClick={() => navigate('/')}
          >
            返回
          </Button>
          <span className="page-title">文章排版</span>
        </div>
        <div className="header-right">
          <Button
            type="primary"
            icon={<ThunderboltOutlined />}
            loading={loading}
            onClick={handleFormat}
            size="large"
          >
            一键排版
          </Button>
          <Button
            icon={<CopyOutlined />}
            onClick={handleCopy}
            disabled={!previewHTML}
            size="large"
          >
            复制到公众号
          </Button>
        </div>
      </header>

      {/* 主内容区 - 三栏布局 */}
      <div className="editor-main">
        {/* 左侧 - 模板选择 */}
        <aside className="editor-sidebar left">
          <h3 className="sidebar-title">选择模板</h3>
          <div className="template-list">
            {templates.map(template => (
              <Card
                key={template.id}
                className={`template-card ${selectedTemplate?.id === template.id ? 'active' : ''}`}
                onClick={() => setSelectedTemplate(template)}
                hoverable
                cover={
                  <div className="template-preview" 
                       style={{ background: template.previewColor || '#f0f7ff' }}>
                    <FileImageOutlined style={{ fontSize: 32, color: '#1890ff' }} />
                  </div>
                }
              >
                <Card.Meta
                  title={template.name}
                  description={template.description}
                />
              </Card>
            ))}
          </div>
        </aside>

        {/* 中间 - 编辑区 */}
        <main className="editor-content">
          <div className="content-section">
            <h3 className="section-title">文章内容</h3>
            <TextArea
              value={content}
              onChange={e => setContent(e.target.value)}
              placeholder="粘贴文章内容...&#10;&#10;支持以下格式：&#10;【标签】标题&#10;——副标题&#10;&#10;正文内容...&#10;&#10;小标题（对偶句或四字格式）&#10;段落内容..."
              className="content-textarea"
              rows={20}
            />
          </div>

          <div className="content-section">
            <h3 className="section-title">上传图片</h3>
            <Upload
              listType="picture-card"
              customRequest={handleImageUpload}
              showUploadList={true}
              multiple
              accept="image/*"
            >
              <div>
                <UploadOutlined />
                <div style={{ marginTop: 8 }}>点击上传</div>
              </div>
            </Upload>
            <p className="upload-tip">支持拖拽上传，建议1200px宽度以内，格式：jpg、png、gif</p>
          </div>
        </main>

        {/* 右侧 - 预览区 */}
        <aside className="editor-sidebar right">
          <h3 className="sidebar-title">预览效果</h3>
          <div className="preview-container">
            {loading ? (
              <div className="preview-loading">
                <Spin size="large" />
                <p>正在生成排版...</p>
              </div>
            ) : previewHTML ? (
              <div 
                className="preview-content"
                dangerouslySetInnerHTML={{ __html: previewHTML }}
              />
            ) : (
              <div className="preview-empty">
                <FileImageOutlined style={{ fontSize: 64, color: '#d9d9d9' }} />
                <p>点击"一键排版"查看效果</p>
              </div>
            )}
          </div>
        </aside>
      </div>
    </div>
  )
}

export default EditorPage

